package Collert

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"models"
	"net/http"
	"pkg"
	"strconv"
	"types"
)

func Order(c *gin.Context) {
	UserId, _ := strconv.Atoi(c.PostForm("user_id"))
	ShopId, _ := strconv.Atoi(c.PostForm("shop_id"))
	OrderNum := c.PostForm("order_num")
	ShopName := c.PostForm("shop_name")
	ShoPrice, _ := strconv.Atoi(c.PostForm("shop_price"))
	OrderStu, _ := strconv.Atoi(c.PostForm("order_stu"))
	PayStu, _ := strconv.Atoi(c.PostForm("pay_stu"))

	pone := models.Order{
		UserId:   UserId,
		ShopId:   ShopId,
		OrderNum: OrderNum,
		ShopName: ShopName,
		ShoPrice: float64(ShoPrice),
		OrderStu: OrderStu,
		PayStu:   PayStu,
	}
	err := pone.OrderAdd()
	tx := types.Db.Begin()
	pkg.Pay(c)
	if err != nil {
		c.JSON(http.StatusBadRequest, types.Router{
			Code:     -1,
			Msg:      "支付失败，请从新支付",
			Database: nil,
		})
		tx.Rollback()
		return
	}
	tx.Commit()

	pkg.NewRabbitMQPubSub("order")
	c.JSON(http.StatusOK, types.Router{
		Code:     200,
		Msg:      "支付成功",
		Database: nil,
	})
}

func OrderDelete(c *gin.Context) {
	Id, _ := strconv.Atoi(c.PostForm("id"))
	pone := models.Order{
		Model: gorm.Model{ID: uint(Id)},
	}
	err := pone.OrderDelete()
	if err != nil {
		c.JSON(http.StatusBadRequest, types.Router{
			Code:     -1,
			Msg:      "删除失败",
			Database: nil,
		})
		return
	}
	c.JSON(http.StatusOK, types.Router{
		Code:     200,
		Msg:      "删除成功",
		Database: nil,
	})
}
